import type { CheckStatusParams, CreateAxiosOptions } from '@wlydfe/service'
import { configureErrorHandler, UrlPrefixEnum, VAxios } from '@wlydfe/service'
import { merge } from 'lodash-es'

import { useUserStore } from '@/store/user'
import { getToken } from '@/utils/auth'

/** 1. 初始化错误处理配置 */
configureErrorHandler({
  /**
   * 1.1 配置toast回调
   *
   * @param message
   * @param status
   */
  onShowToast: (message: string, status?: number | string): void => {
    console.log('Show toast:', message, 'Status:', status)
    // TODO: 实际的toast逻辑
    ElMessage.error(message)
  },

  /**
   * 1.2 配置检查状态回调
   *
   * @param root0 检查状态参数
   * @param root0.errCode 错误码
   * @param root0.errMsg 错误信息
   * @param root0.err 错误对象
   */
  checkStatus: ({ errCode, errMsg, err }: CheckStatusParams): void => {
    console.log(`Check status: ${errCode}, Message: ${errMsg}, err: ${err}`)
    // token 失效
    const tokenErrCodes: (string | number)[] = ['PLATFROM0101', 'ACOM0004']
    if (tokenErrCodes.includes(errCode)) {
      const userStore = useUserStore()
      userStore.doLogout()
    }
  },
})

/** 2. 默认请求配置 */
const defaultOptions: CreateAxiosOptions = {
  headers: {
    systype: '31',
  },
  requestOptions: {
    // 根地址
    // baseURL: import.meta.env.VITE_BASE_URL,
    // url前缀
    urlPrefix: UrlPrefixEnum.DEFAULT,
    // 获取token的函数
    getToken: () => getToken() || '',
  },
}

/**
 * 3. 创建axios实例
 *
 * @param opt
 */
const createAxios = (opt?: Partial<CreateAxiosOptions>) => {
  // merge: 深度合并
  return new VAxios(merge(defaultOptions, opt || {}))
}

/** 4. 导出axios实例 */
const http = createAxios()
export default http
